package com.gz;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {

	private Socket socket;
	private InputStream in;
	private PrintStream out;
	public static final String WEB_ROOT = "E:\\workspace\\WebServer\\webServer\\WEB_ROOT";

	public Processor() {

	}

	public Processor(Socket socket) {
		this.socket = socket;
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		String fileName = process(in);
		sendFile(fileName);
	}

	private String process(InputStream in) {
		String fileName = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		try {
			String str = br.readLine();
			String[] content = str.split(" ");
			fileName = content[1];

			System.out.println("code:" + content[0] + ",fileName:" + content[1] + ",version:" + content[2]);

		} catch (IOException e) {
			e.printStackTrace();
		}

		return fileName;

	}

	private void sendMsg(int errorCode, String errorMsg) {
		out.println("HTTP/1.0 errorCode:" + errorCode + ",errorMsg:" + errorMsg);
		out.println("content-type:http/html");

	}

	private void sendFile(String fileName) {
		File file = new File(WEB_ROOT + fileName);
		System.out.println("file....");
		if (!file.exists()) {
			sendMsg(404, "File Not Found");
			return;
		}

		try {
			FileInputStream in = new FileInputStream(file);
			byte[] content = new byte[(int) file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 success");
			out.println("content-length:" + content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
